package com.chezai.client.update;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import com.chezai.client.global.Const;
import com.chezai.client.global.DeviceFactory;
import com.chezai.client.global.NetConst;
import com.chezai.client.global.TerminalApplication;
import com.chezai.client.server.util.VersionUpdataHelper;
import com.chezai.client.utils.DeviceUtils;
import com.chezai.client.utils.PackageUtils;
import com.chezai.client.utils.SDCardUtil;
import com.orhanobut.logger.Logger;

import org.xutils.common.Callback;
import org.xutils.common.task.PriorityExecutor;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.lang.ref.SoftReference;
import java.util.List;
import java.util.concurrent.Executor;

/**
 * 应用升级管理类
 * Created by likunyang on 2017/9/5.
 */

public class AppUpdateManager {
    private final static int MAX_DOWNLOAD_THREAD = 2; // 有效的值范围[1, 3]
    private static AppUpdateManager newInstance;
    private final Executor executor = new PriorityExecutor(MAX_DOWNLOAD_THREAD, true);
    private final String tempDir;
    private RequestParams downloadParams;
    private String TAG = this.getClass().getSimpleName();
    private boolean isUpdating = false;
    private Callback.Cancelable cancelable;
    private Callback.Cancelable downloadCallBack;
    private String url;
    private String fileName;
    private String currentVersion;
    private OnUpdateListener mUpdateListener;

    private AppUpdateManager() {
        downloadParams = initDownloadParams();
        tempDir = SDCardUtil.getDownloadDir();
    }

    public static AppUpdateManager getInstance() {
        if (newInstance == null) {
            newInstance = new AppUpdateManager();
        }
        return newInstance;
    }

    private RequestParams initDownloadParams() {
        downloadParams = new RequestParams();
        downloadParams.setAutoResume(false);
        downloadParams.setAutoRename(false);
        downloadParams.setExecutor(executor);
        downloadParams.setCancelFast(false);
        return downloadParams;
    }

    public void setOnUpdateListener(OnUpdateListener listner) {
        this.mUpdateListener = listner;
    }

    /**
     * 是否在升级中
     *
     * @return true 是，false 否
     */
    public boolean isUpdating() {
        return isUpdating;
    }

    public void setUpdating(boolean isUpdating) {
        this.isUpdating = isUpdating;
    }

   /* private RequestParams getRequestParams() {
        currentVersion = PackageUtils.getVersionName(new SoftReference<Context>(TerminalApplication.getTerminalContext()));
        String channelModel = TerminalApplication.channelModel;
        StringBuilder sb = new StringBuilder();
        sb.append(NetConst.TERMINAL_UPDATE_UPGRADER);
        sb.append(channelModel);
        sb.append("/");
        sb.append(currentVersion);
        sb.append("/");
        sb.append(DeviceFactory.getInstance().getHardware().getImei(TerminalApplication.mContext));
        Logger.t(TAG).i("检测升级Url:" + sb.toString());
        RequestParams requestParams = new RequestParams(sb.toString());
        return requestParams;
    }*/
   private RequestParams getRequestParams() {
       currentVersion = PackageUtils.getVersionCode(new SoftReference<Context>(TerminalApplication.getTerminalContext()))+"";
       String channelModel = TerminalApplication.channelModel;
       StringBuilder sb = new StringBuilder();
       sb.append(NetConst.UPGRADER_URL);
       sb.append(channelModel);
       sb.append("/");
       sb.append(currentVersion);
       sb.append("/");
       sb.append(DeviceFactory.getInstance().getHardware().getImei(TerminalApplication.mContext));
       Logger.t(TAG).i("检测升级Url:" + sb.toString());
       RequestParams requestParams = new RequestParams(sb.toString());
       return requestParams;
   }

    /**
     * 获取应用升级信息
     */
    /*public void getUpdateInfo() {
        Logger.t(TAG).i("开始检查升级。");
        if (isUpdating) return;
        cancelable = x.http().get(getRequestParams(), new Callback.CommonCallback<List<AppUpdateInfo>>() {
            @Override
            public void onSuccess(List<AppUpdateInfo> result) {
                Logger.t(TAG).i("检查升级成功。");
                if (result != null) {
                    findMaxCode(result);
                    if (!TextUtils.isEmpty(url)) {
                        isUpdating = true;
                        Logger.t(TAG).i("最新版本下载地址：" + url);
                        Intent intent = new Intent(Const.UPDATE_APP);
                        intent.putExtra("url", url);
                        TerminalApplication.getTerminalContext().sendBroadcast(intent);
                    } else {
                        isUpdating = false;
                    }
                    if (mUpdateListener != null) {
                        mUpdateListener.getUpdateInfoSucess(isUpdating);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Logger.t(TAG).e("检查升级OnError。" + ex.getMessage());
                isUpdating = false;
                if (mUpdateListener != null) {
                    mUpdateListener.getUpdateInfoFailed();
                }
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Logger.t(TAG).i("检查升级取消。");
                isUpdating = false;
            }

            @Override
            public void onFinished() {
                Logger.t(TAG).i("检查升级Finished");
                isUpdating = false;
            }
        });
    }*/

    public void getUpdateInfo(final Activity activity) {
        Logger.t(TAG).i("开始检查升级。");
        if (isUpdating) return;
        cancelable = x.http().get(getRequestParams(), new Callback.CommonCallback<List<AppUpdateInfo>>() {
            @Override
            public void onSuccess(List<AppUpdateInfo> result) {
                Logger.t(TAG).i("检查升级成功。");
                if (result != null) {
                    //harisucici
                    findMaxCode(result);
                    if (!TextUtils.isEmpty(url)) {
                        isUpdating = true;
                        Logger.t(TAG).i("最新版本下载地址：" + url);
                        new VersionUpdataHelper(activity, url, false);
                    } else {
                        isUpdating = false;
                    }
                    if (mUpdateListener != null) {
                        mUpdateListener.getUpdateInfoSucess(isUpdating);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Logger.t(TAG).e("检查升级OnError。" + ex.getMessage());
                isUpdating = false;
                if (mUpdateListener != null) {
                    mUpdateListener.getUpdateInfoFailed();
                }
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Logger.t(TAG).i("检查升级取消。");
                isUpdating = false;
            }

            @Override
            public void onFinished() {
                Logger.t(TAG).i("检查升级Finished");
                isUpdating = false;
            }
        });
    }


    private void findMaxCode(List<AppUpdateInfo> result) {
        String[] current = currentVersion.split("\\.");//{1,2,4}
        if (result.size() == 0) return;
        for (AppUpdateInfo info : result) {
            String[] split = info.getCode().split("\\.");//{2,3,4}
            for (int i = 0; i < Math.min(current.length, split.length); i++) {
                int c = Integer.parseInt(current[i]);
                int s = Integer.parseInt(split[i]);
                if (s > c) {
                    current = split;
                    url = info.getUrl();
                    Logger.t(TAG).d("code :" + info.getCode());
                    break;
                } else if (s == c) {
                    continue;
                } else {
                    break;
                }
            }
        }
    }

    /**
     * 下载
     *
     * @param url      下载地址
     * @param dirPath  下载文件保存的文件夹地址
     * @param fileName 保存的文件名
     */
    public void download(String url, String dirPath, String fileName) {
        Logger.t(TAG).d("开始下载 文件名：" + fileName + " 保存地址：" + dirPath);
        this.fileName = fileName;
        DownloadCallback callback = new DownloadCallback();
        downloadParams.setUri(url);
        downloadParams.setSaveFilePath(dirPath + fileName);
        downloadCallBack = x.http().get(downloadParams, callback);
        callback.setCancelable(downloadCallBack);
    }

    /**
     * 重新下载
     */
    public void reload() {
        download(url, tempDir, fileName);
    }

    /**
     * 取消下载
     */
    public void cancelDownload() {
        if (isUpdating && downloadCallBack != null && !downloadCallBack.isCancelled()) {
            downloadCallBack.cancel();
        }
    }

    public void unRegisterListener() {
        if (mUpdateListener != null) {
            this.mUpdateListener = null;
        }
    }
}
